import { ipcMain, dialog } from 'electron'
import json2xls from 'json2xls'
import fs from 'fs'
import {
  IVulDetailsRootObject,
  IVulnerabilityInformationListParams,
  IVulnerabilityInformationListRecord
} from '../types'
import { getVulDetails, getVulnList } from './apis/VulnerabilityInformationApis'
import { getLabelList, hazardLevelOptions } from './common/localDict'

const iconPath = '/Users/hope/sdy/cnnvd-desk-application/src/renderer/src/assets/maozhua.png'

ipcMain.on('getVulnerList', async (_event, arg: IVulnerabilityInformationListParams) => {
  const res = await getVulnList(arg)
  _event.returnValue = res.data
})
ipcMain.on(
  'exportVulnerabilityInformationList',
  async (_event, arg: IVulnerabilityInformationListParams[]) => {
    // getVuListDataDetails 获取列表的全部详情，并且返回！
    function getVuListDataDetails(
      list: IVulnerabilityInformationListRecord[]
    ): Promise<IVulDetailsRootObject[]> {
      return new Promise((resolve, reject) => {
        const pa = list.map((item) =>
          getVulDetails({
            id: item.id,
            vulType: item.vulType,
            cnnvdCode: item.cnnvdCode
          })
        )
        Promise.all(pa)
          .then((r) => {
            resolve(r)
          })
          .catch((e) => {
            reject(e)
          })
          .finally(() => {})
      })
    }
    // 根据参数获取详情！
    async function getParamsList(
      _params: IVulnerabilityInformationListParams
    ): Promise<IVulDetailsRootObject[]> {
      return new Promise(async (resolve) => {
        let arr: IVulDetailsRootObject[] = []
        const listData = await getVulnList(_params)
        // 先根据参数获取列表数据！
        // const detailsList = await getVuListDataDetails(listData.data.records)
        // arr = [...arr, ...detailsList]
        // 根据列表数据 获取 total
        const total = listData.data.total
        console.log({ total })
        console.log('arr.length', arr.length)
        while (arr.length < total) {
          const listData = await getVulnList(_params)
          const detailsList = await getVuListDataDetails(listData.data.records)
          arr = [...arr, ...detailsList]
          _params.pageIndex += 1
        }
        console.log(arr.length)

        resolve(arr)
      })
    }
    let details: IVulDetailsRootObject[] = []
    const exportParams = arg.map((v) => {
      return {
        pageIndex: 1,
        pageSize: 100,
        keyword: '',
        hazardLevel: v.hazardLevel,
        vulType: v.vulType,
        vendor: '',
        product: '',
        dateType: v.dateType,
        beginTime: v.beginTime,
        endTime: v.endTime
      }
    })
    for (let i = 0; i < exportParams.length; i++) {
      const arr = await getParamsList(exportParams[i] as IVulnerabilityInformationListParams)
      details = [...details, ...arr]
    }
    const finallyResult = details
      .map((v) => v.data.cnnvdDetail)
      .map((v) => {
        const needParams = {}
        needParams['漏洞名称'] = v.vulName
        needParams['cnnvd编号'] = v.cnnvdCode
        needParams['cve编号'] = v.cveCode
        needParams['收录时间'] = v.publishTime
        needParams['危害级别'] = getLabelList(v.hazardLevel, hazardLevelOptions)
        needParams['漏洞描述'] = v.vulDesc
        needParams['漏洞来源'] = v.referUrl
        needParams['解决方案'] = v.patch
        return needParams
      })
    const xls = json2xls(finallyResult)
    const saveObject = await dialog.showSaveDialog({
      title: '导出漏洞详情'
    })
    if (saveObject.filePath) {
      fs.writeFileSync(saveObject.filePath + '.xlsx', xls, 'binary')
    }
    dialog.showMessageBox({
      title: '成功！',
      icon: iconPath,
      message: `漏洞信息导出成功！本次导出了${finallyResult.length}条数据`,
      buttons: ['蟹蟹 To志红的臭宝']
    })
    _event.returnValue = 1
  }
)
